var request = require('request');
var querystring = require('querystring')
var Fiber = require('fibers');
var ak = "Cjm0Sm7N0P2rTgpF2tEw1tg1";
var geotable_id = "92810"

module.exports = {
	get: function(id) {
		var fiber = Fiber.current;
		var _err;
		var _res;
		request.get("http://api.map.baidu.com/geodata/v2/poi/detail?" + querystring.stringify({
			ak: ak,
			geotable_id: geotable_id,
			id: id
		}), function(err, httpResponse, body) {
			_err = err;
			_res = body;
			fiber.run();
		});
		Fiber.yield(); //挂起
		if (_err) {
			throw _err;
		}
		_res = JSON.parse(_res);
		if (_res.status != 0) {
			throw _res.message;
		}
		return _res.poi;
	},
	create: function(opts) {
		var formData = {
			ak: ak,
			title: opts.title,
			address: opts.address,
			latitude: opts.lat,
			longitude: opts.lon,
			logo: opts.logo_url,
			mobile: opts.mobile_phone,
			coord_type: 1,
			geotable_id: geotable_id,
		};
		var fiber = Fiber.current;
		var _err;
		var _res;
		var res = request.post({
			url: 'http://api.map.baidu.com/geodata/v2/poi/create',
			formData: formData
		}, function optionalCallback(err, httpResponse, body) {
			_err = err;
			_res = body;
			fiber.run();
		});
		Fiber.yield(); //挂起
		if (_err) {
			throw _err;
		}
		_res = JSON.parse(_res);
		if (_res.status != 0) {
			throw _res.message;
		}
		return _res.id;
	},
	update: function(id, opts) {
		var formData = {
			ak: ak,
			id: id,
			title: opts.title,
			address: opts.address,
			latitude: opts.lat,
			longitude: opts.lon,
			logo: opts.logo_url,
			mobile: opts.mobile_phone,
			coord_type: 1,
			geotable_id: geotable_id,
		};
		var fiber = Fiber.current;
		var _err;
		var _res;
		var res = request.post({
			url: 'http://api.map.baidu.com/geodata/v2/poi/update',
			formData: formData
		}, function optionalCallback(err, httpResponse, body) {
			_err = err;
			_res = body;
			fiber.run();
		});
		Fiber.yield(); //挂起
		if (_err) {
			throw _err;
		}
		_res = JSON.parse(_res);
		if (_res.status != 0) {
			throw _res.message;
		}
	}
};

// /*TEST*/
// Fiber(function() {
// 	var id = module.exports.create({
// 		title: "node测试",
// 		address: "我家你要我",
// 		lat: "20",
// 		lon: "20",
// 		logo_url: "http://o2oimg.qiniudn.com/FqYeh139jPDScF7EpRLYuP55kDp5",
// 		mobile_phone: "15659444549"
// 	});
// 	module.exports.update(id, {
// 		title: "node测试2",
// 		address: "我家你要我",
// 		lat: "30",
// 		lon: "40",
// 		logo_url: "http://o2oimg.qiniudn.com/FqYeh139jPDScF7EpRLYuP55kDp5",
// 		mobile_phone: "15659444549"
// 	})
// 	var poi = module.exports.get(id);
// 	console.log(poi);
// }).run();